package com.sjz.ctkj.canvasstudy.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;


import com.sjz.ctkj.canvasstudy.base.MyApp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 作者：石天彪
 * 创建时间：2017/3/6 12:37
 * 最后一次修改时间：
 * 必传参数 (TODO )
 * 描述：工具类
 */
public class SysUtils {

    /**
     * webview对图片进行重置大小，宽度就是手机屏幕宽度，高度根据宽度比便自动缩放
     **/ public static void imgReset(WebView webView) {
        webView.loadUrl("javascript:(function(){" + "var objs = document.getElementsByTagName('img'); " + "for(var i=0;i<objs.length;i++)  " + "{" + "var img = objs[i];   " + "    img.style.maxWidth = '100%'; img.style.height = 'auto';  " + "}" + "})()");
    }

    /**
     * 转换Pixel为dp
     */
    public static int convertPixelToDp(Context context, float px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }
    /**
     * 将dp转换成px
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue){
        final float scale = context.getResources ().getDisplayMetrics ().density;
        return (int) (dpValue * scale + 0.5f);
    }


    /**
     * 获得当前应用版本名称
     */
    public static String getAppVersion(Context context) {
        String versionName = "";
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            versionName = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 获得当前应用版本号
     */
    public static int getAppVersionNum() {
        int versionCode = 0;
        Application app = MyApp.getMyApp();
        PackageManager manager = app.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(app.getPackageName(), 0);
            versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
    /**
     * 判断SD卡是否存在
     *
     * @return
     */
    public static boolean isExternalStorageAvailable() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }




    /**
     * 是否全部是汉字
     *
     * @param str
     * @return true 全中文   false 有其他字符
     */
    public static boolean isAllChinese(String str) {

        Pattern p = Pattern.compile("[^\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return false;
        }
        return true;
    }

    /**
     * 判断只允许字母、数字和汉字(不允许有表情符号)
     *
     * @param str
     * @return true 全中文   false 有其他字符
     */
    public static boolean isNoEmoticon(String str) {
        String regEx = "[^a-zA-Z0-9@\\.\u4E00-\u9FA5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        if (m.find()) {
            return false;
        }
        return true;
    }

    /**
     * 只允许字母、数字和汉字
     *
     * @param str
     * @return
     */
    public static String stringFilter(String str) {
        String regEx = "[^a-zA-Z0-9@\\.\u4E00-\u9FA5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 提取电话号码
     */
    public static List<String> extractPhones(String text) {
        List<String> result = new ArrayList<String>();
        char ch;
        text = text.trim();
        StringBuffer buff = null;
        for (int i = 0; i < text.length(); i++) {
            ch = text.charAt(i);
            if ((ch >= '0' && ch <= '9') || ch == '-') {
                if (buff == null) {
                    buff = new StringBuffer();
                }
                buff.append(ch);
                if (i == text.length() - 1) {
                    result.add(buff.toString());
                }
            } else {
                if (buff != null) {
                    result.add(buff.toString());
                    buff = null;
                }
            }
        }
        buff = null;
        return result;
    }

    /**
     * 获得屏幕尺寸
     */
    public static int[] getScreenSize(Context context) {
        int[] size = new int[2];
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        size[0] = outMetrics.widthPixels;
        size[1] = outMetrics.heightPixels;
        return size;
    }

    /**
     * 去掉字符串两边的空格，包括全角和半角的空格
     */
    public static String trim(String str) {
        String result = str.trim().replaceAll("^[　*| *]*", "")
                .replaceAll("[　*| *]*$", "");
        return result;
    }

    /**
     * 判断软键盘是否打开 若返回true，则表示输入法打开
     */
    public static boolean isSoftKeyboardShow() {
        MyApp app = MyApp.getMyApp();
        InputMethodManager imm = (InputMethodManager) app
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null)
            return false;
        return imm.isActive();
    }

    public static boolean isSoftKeyboardShow(View v) {
        MyApp app = MyApp.getMyApp();
        InputMethodManager imm = (InputMethodManager) app
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null)
            return false;
        return imm.isActive(v);
    }

    /**
     * 显示、隐藏软键盘
     */
    public static void showSoftKeyboard(View v, boolean isShow) {
        MyApp app = MyApp.getMyApp();
        InputMethodManager imm = (InputMethodManager) app
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (isShow) {
            imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
        } else {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**
     * 判断GPS是否打开
     */
    public static boolean isGpsEnabled(Context context) {
        LocationManager lm = ((LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE));
        List<String> accessibleProviders = lm.getProviders(true);
        if (accessibleProviders == null || accessibleProviders.size() <= 0) {
            return false;
        }
        boolean gps = false;
        for (String provider : accessibleProviders) {
            if (provider.equals(LocationManager.GPS_PROVIDER)) {
                gps = true;
                break;
            }
        }
        return gps;
    }

    /**
     * 判断网络连接是否可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
        } else {
            // 如果仅仅是用来判断网络连,则可以使用 cm.getActiveNetworkInfo().isAvailable();
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 检查是否为完整的身份证号码
     */
    public static class CheckIdCard {
        private String cardNumber; // 完整的身份证号码
        private Boolean cacheValidateResult = null; // 缓存身份证是否有效，因为验证有效性使用频繁且计算复杂
        private Date cacheBirthDate = null; // 缓存出生日期，因为出生日期使用频繁且计算复杂
        private final static String BIRTH_DATE_FORMAT = "yyyyMMdd"; // 身份证号码中的出生日期的格式
        private final Date MINIMAL_BIRTH_DATE = new Date(-2209017600000L); // 身份证的最小出生日期,1900年1月1日
        private final static int NEW_CARD_NUMBER_LENGTH = 18;
        private final static int OLD_CARD_NUMBER_LENGTH = 15;
        private final static char[] VERIFY_CODE = {'1', '0', 'X', '9', '8',
                '7', '6', '5', '4', '3', '2'}; // 18位身份证中最后一位校验码
        private final static int[] VERIFY_CODE_WEIGHT = {7, 9, 10, 5, 8, 4, 2,
                1, 6, 3, 7, 9, 10, 5, 8, 4, 2};// 18位身份证中，各个数字的生成校验码时的权值

        public boolean validate() {
            if (null == cacheValidateResult) {
                boolean result = true;
                result = result && (null != cardNumber); // 身份证号不能为空
                result = result
                        && NEW_CARD_NUMBER_LENGTH == cardNumber.length(); // 身份证号长度是18(新证)
                // 身份证号的前17位必须是阿拉伯数字
                for (int i = 0; result && i < NEW_CARD_NUMBER_LENGTH - 1; i++) {
                    char ch = cardNumber.charAt(i);
                    result = result && ch >= '0' && ch <= '9';
                }
                // 身份证号的第18位校验正确
                result = result
                        && (calculateVerifyCode(cardNumber) == cardNumber
                        .charAt(NEW_CARD_NUMBER_LENGTH - 1));
                // 出生日期不能晚于当前时间，并且不能早于1900年
                try {
                    Date birthDate = this.getBirthDate();
                    result = result && null != birthDate;
                    result = result && birthDate.before(new Date());
                    result = result && birthDate.after(MINIMAL_BIRTH_DATE);
                    /**
                     * 出生日期中的年、月、日必须正确,比如月份范围是[1,12],日期范围是[1,31]，还需要校验闰年、大月、
                     * 小月的情况时， 月份和日期相符合
                     */
                    String birthdayPart = this.getBirthDayPart();
                    String realBirthdayPart = this.createBirthDateParser()
                            .format(birthDate);
                    result = result && (birthdayPart.equals(realBirthdayPart));
                } catch (Exception e) {
                    result = false;
                }
                cacheValidateResult = Boolean.valueOf(result);
                // 完整身份证号码的省市县区检验规则
            }
            return cacheValidateResult;
        }

        /**
         * 如果是15位身份证号码，则自动转换为18位
         */
        public CheckIdCard(String cardNumber) {
            if (null != cardNumber) {
                cardNumber = cardNumber.trim();
                if (OLD_CARD_NUMBER_LENGTH == cardNumber.length()) {
                    cardNumber = contertToNewCardNumber(cardNumber);
                }
            }
            this.cardNumber = cardNumber;
        }

        public String getCardNumber() {
            return cardNumber;
        }

        public String getAddressCode() {
            this.checkIfValid();
            return this.cardNumber.substring(0, 6);
        }

        public Date getBirthDate() {
            if (null == this.cacheBirthDate) {
                try {
                    this.cacheBirthDate = this.createBirthDateParser().parse(
                            this.getBirthDayPart());
                } catch (Exception e) {
                    throw new RuntimeException("身份证的出生日期无效");
                }
            }
            return new Date(this.cacheBirthDate.getTime());
        }

        public boolean isMale() {
            return 1 == this.getGenderCode();
        }

        public boolean isFemal() {
            return false == this.isMale();
        }

        /**
         * 获取身份证的第17位，奇数为男性，偶数为女性
         */
        private int getGenderCode() {
            this.checkIfValid();
            char genderCode = this.cardNumber
                    .charAt(NEW_CARD_NUMBER_LENGTH - 2);
            return (((int) (genderCode - '0')) & 0x1);
        }

        public String getBirthDayPart() {
            return this.cardNumber.substring(6, 14);
        }

        @SuppressLint("SimpleDateFormat")
        private SimpleDateFormat createBirthDateParser() {
            return new SimpleDateFormat(BIRTH_DATE_FORMAT);
        }

        public boolean checkIfValid() {
            if (false == this.validate()) {
                return false; // 验证格式错误
            }
            return true; // 格式正确
        }

        /**
         * 校验码（第十八位数）：
         * <p/>
         * 十七位数字本体码加权求和公式 S = Sum(Ai * Wi), i = 0...16 ，先对前17位数字的权求和；
         * Ai:表示第i位置上的身份证号码数字值 Wi:表示第i位置上的加权因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5
         * 8 4 2; 计算模 Y = mod(S, 11)< 通过模得到对应的校验码 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码:
         * 1 0 X 9 8 7 6 5 4 3 2
         *
         * @param cardNumber
         * @return
         */
        private static char calculateVerifyCode(CharSequence cardNumber) {
            int sum = 0;
            for (int i = 0; i < NEW_CARD_NUMBER_LENGTH - 1; i++) {
                char ch = cardNumber.charAt(i);
                sum += ((int) (ch - '0')) * VERIFY_CODE_WEIGHT[i];
            }
            return VERIFY_CODE[sum % 11];
        }

        /**
         * 把15位身份证号码转换到18位身份证号码<br>
         * 15位身份证号码与18位身份证号码的区别为：<br>
         * 1、15位身份证号码中，"出生年份"字段是2位，转换时需要补入"19"，表示20世纪<br>
         * 2、15位身份证无最后一位校验码。18位身份证中，校验码根据根据前17位生成
         *
         * @return
         */
        private String contertToNewCardNumber(String oldCardNumber) {
            StringBuilder buf = new StringBuilder(NEW_CARD_NUMBER_LENGTH);
            buf.append(oldCardNumber.substring(0, 6));
            buf.append("19");
            buf.append(oldCardNumber.substring(6));
            buf.append(CheckIdCard.calculateVerifyCode(buf));
            return buf.toString();
        }
    }

    /**
     * 上传图片压缩
     *
     * @param imagePath 要上传的图片路径
     * @return 压缩之后的图片路径
     */
    public static String compressUploadImage(String imagePath) {
        File file = null;
        file = new File(imagePath);
        if (file.length() / 1024 > 500) {// 如果图片大小大于500K,压缩图片
            ByteArrayOutputStream baos = null;
            FileOutputStream fileOutputStream = null;
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;// 先得到图片信息
                BitmapFactory.decodeFile(imagePath, options);
                final int height = options.outHeight;
                final int width = options.outWidth;
                int inSampleSize = 1;
                if (height > 800 || width > 480) {// 默认按照480*800进行压缩
                    final int heightRatio = Math.round((float) height / 800);
                    final int widthRatio = Math.round((float) width / 480);
                    inSampleSize = heightRatio < widthRatio ? heightRatio
                            : widthRatio;
                }
                options.inSampleSize = inSampleSize;// 赋值缩放比
                options.inJustDecodeBounds = false;
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
                baos = new ByteArrayOutputStream();

                int quality = 90;// 初始化压缩质量
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
                while (baos.toByteArray().length / 1024 > 500) {// 如果图片大小>500K继续进行质量压缩
                    baos.reset();
                    quality -= 10;
                    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
                }

                String fileType = imagePath.substring(imagePath.lastIndexOf("."), imagePath.length());
                file = new File(MyApp.getMyApp().getCacheDir()
                        .getPath() + File.separator + "upload" + System.currentTimeMillis() + fileType);
                if (!file.getParentFile().exists())
                    file.getParentFile().mkdirs();
                if (!file.exists())
                    file.createNewFile();
                fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(baos.toByteArray());
                fileOutputStream.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (baos != null) {
                        baos.close();
                    }
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file.getPath();
    }


    /**
     * @return 参数说明
     * @methods isInAvoidTime
     * @description 判断当前是否在免打扰时间段
     * @date 2015-7-2 下午3:52:12
     */
    public static boolean isInAvoidTime() {
        Calendar calendar = Calendar.getInstance(Locale.getDefault());
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        return hour < 22 && hour > 8;
    }



    /**
     * 设置屏幕亮度
     *
     * @param context
     * @param alpha
     */
    public static void setWindowAlpha(Context context, float alpha) {
        WindowManager.LayoutParams lp = ((Activity) context).getWindow().getAttributes();
        lp.alpha = alpha; //0.0-1.0
        ((Activity) context).getWindow().setAttributes(lp);
    }

    private static long lastClickTime = 0;
    public static boolean clickFilter() {
        final long INTERVAL = 500L; //防止连续点击的时间间隔
        long time = System.currentTimeMillis();
        if ((time - lastClickTime) > INTERVAL) {
            lastClickTime = time;
            return true;
        } else {
            lastClickTime = time;
        }
        return false;
    }

    /**
     * @param
     * @return 返回值
     * @description 判断包名为packageName的应用是否存活
     */
    public static boolean isAppAlive(Context context, String packageName) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processInfos = activityManager.getRunningAppProcesses();
        for (int i = 0; i < processInfos.size(); i++) {
            if (processInfos.get(i).processName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }



    // 加密
    public static String getBase64(String str) {
        String result = "";
        if (str != null) {
            try {
                result = new String(Base64.encode(str.getBytes("utf-8"), Base64.NO_WRAP), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获取sha1值
     *
     * @param context
     * @return
     */
    public static String getSHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuilder hexString = new StringBuilder();
            for (byte aPublicKey : publicKey) {
                String appendString = Integer.toHexString(0xFF & aPublicKey).toUpperCase(Locale.US);
                if (appendString.length() == 1) {
                    hexString.append("0");
                }
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 转换dp为Pixel
     */
    public static float convertDpToPixel(int dp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                MyApp.getMyApp().getResources().getDisplayMetrics());
    }

    /**
     * 保留两位小数(四舍五入)
     */
    public static String formatDouble(double d) {
        DecimalFormat df = new DecimalFormat("#.00");
        if (d == 0) {
            return "0.00";
        } else {
            return df.format(d);
        }

    }

    /**
     * 保留两位小数(四舍五入)
     */
    public static String formatDoubleNew(double d) {
        DecimalFormat df = new DecimalFormat("#.00");
        if (d == 0) {
            return "0.00";
        } else if (d > 0 && d < 1) {
            return "0" + df.format(d);
        } else {
            return df.format(d);
        }
    }

    /**
     * 保留两位小数(去掉0。21.501显示21.5)
     */
    public static String formatDoubleDecimal(double d) {
        DecimalFormat df = new DecimalFormat("###.##");
        if (d == 0) {
            return "0";
        } else {
            return df.format(d);
        }
    }
    /**
     * 关闭软键盘
     * @param context
     */
    public static void closeKeyboard(Activity context) {
        View view = context.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 返回
     * @param context
     * @param resultCode
     */
    public static void rebackResult(Activity context, int resultCode){
        Intent intent = new Intent();
        context.setResult(resultCode,intent);
        context.finish();
    }

    /**
     * 获取程序版本号
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
    /**
     * 获取程序版本号
     * @param mContext
     * @return
     */
    public static String getVersionName(Context mContext) {
        String versionName = "";
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionName = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    /**
     * 截取字符串变为**
     * @param str
     * @return
     */
    public static String subStringRepalceXing(String str){
        String rebackString="";
        if(str!=null&&!"".equals(str)){
            String two = str.substring(1,str.length());
            rebackString = str.replace(two,"**");
        }
        return  rebackString;
    }
    /**
     * 获取手机信息
     * */
    public String getPhoneInfo(Context context){

        String id = "NO Search";

        id = android.provider.Settings.Secure.getString(

                context.getContentResolver(),

                android.provider.Settings.Secure.ANDROID_ID);



        return id;
    }

    /**
     * 使用AudioManager控制音量
     *
     * @param value
     * @param context
     */
    private void setVoiceVolume(float value, Context context) {
        try {
            AudioManager audioManager = (AudioManager) context.getSystemService(Service.AUDIO_SERVICE);
            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//(最大值是15)
            int flag = value > 0 ? -1 : 1;
            currentVolume += flag * 0.1 * maxVolume;
            // 对currentVolume进行限制
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * @param volume 音量大小
     * @param object VideoView实例
     *               ///VideoView 反射 MediaPlayer控制音量 http://blog.csdn.net/u012874222/article/details/73303264
     *               静音有效果,恢复无效
     */
    private void setVolume(float volume, Object object) {
        try {
            Class<?> forName = Class.forName("android.widget.VideoView");
            Field field = forName.getDeclaredField("mMediaPlayer");
            field.setAccessible(true);
            MediaPlayer mMediaPlayer = (MediaPlayer) field.get(object);
            mMediaPlayer.setVolume(volume, volume);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

